import $http from '@/config/requestConfig'
import store from '@/store';
import base from '@/config/baseUrl';
import md5 from '@/config/md5.js';
import { getAppWxLatLon } from '@/plugins/utils';
// #ifdef H5
import { getLatLonH5, publicShareFun, wxPublicPay, getBrowser,appMutual } from '@/config/html5Utils';
// 公众号分享
export const publicShare = publicShareFun;
// #endif
// #ifdef APP-PLUS
import appShareFun, {closeShare} from '@/uni_modules/zhouWei-APPshare/js_sdk/appShare';
// APP分享
export const appShare = function(data,callbcak){
	let userInfo = store.state.userInfo;
	if(!(userInfo && userInfo.uid)){
		userInfo = uni.getStorageSync("userInfo");
	}
	let shareData = {
		shareTitle: data.shareTitle || base.share.title,
		shareUrl: data.shareUrl || base.share.link,
		shareContent: data.shareContent || base.share.desc,
		shareImg: data.shareImg || base.share.imgUrl,
	}
	if (userInfo && userInfo.uid) {
		if(data.shareUrl){
			if(data.shareUrl.indexOf("?") >= 0){
				shareData.shareUrl = data.shareUrl + "&recommend=" + userInfo.uid
			} else {
				shareData.shareUrl = data.shareUrl + "?recommend=" + userInfo.uid
			}
		} else if(base.share && base.share.link){
			if(base.share.link.indexOf("?") >= 0){
				shareData.shareUrl = base.share.link + "&recommend=" + userInfo.uid
			} else {
				shareData.shareUrl = base.share.link + "?recommend=" + userInfo.uid
			}
		}
	}
	return appShareFun({
		shareTitle: data.shareTitle || base.share.title,
		shareUrl: data.shareUrl || base.share.link,
		shareContent: data.shareContent || base.share.desc,
		shareImg: data.shareImg || base.share.imgUrl,
	},callbcak);
};
export const closeAppShare = closeShare;
// #endif

// #ifdef MP-WEIXIN
// 微信小程序分享
export const wxShare = function (data = {}) {
	let shareInfo = {
		title: data.title || base.share.title,
	};
	if(data.path && typeof(data.path) == "string"){
		shareInfo.path = data.path;
	} else if(data.path != 1){
		shareInfo.path = "pages/home/home";
	}
	if(data.imageUrl){
		shareInfo.imageUrl = data.imageUrl;
	}
	let userInfo = store.state.userInfo;
	if(!(userInfo && userInfo.uid)){
		userInfo = uni.getStorageSync("userInfo");
	}
	if (userInfo && userInfo.uid) {
		if(data.query && typeof(data.query) == "object"){
			data.query.recommendCode = userInfo.uid;
		} else {
			data.query = {
				recommendCode: userInfo.uid
			};
		}
	}
	if(data.query && typeof(data.query) == "object"){
		Object.keys(data.query).forEach((key,index) => {
			if(index > 0 && shareInfo.query){
				shareInfo.query += "&" + key + "=" + data.query[key];
				shareInfo.path += "&" + key + "=" + data.query[key];
			} else {
				shareInfo.query = key + "=" + data.query[key];
				shareInfo.path += "?" + key + "=" + data.query[key];
			}
		});
	}
	return shareInfo;
}
// #endif

//支付（APP微信支付、APP支付宝支付、微信小程序支付）
export const setPay = function(payInfo, callback) {
	let httpUrl = "";
	if (payInfo.type == 'wxpay') {
		// APP微信支付
		httpUrl = 'api/pay/v1/pay_sign_wx'
	} else if (payInfo.type == 'alipay') {
		// APP支付宝支付
		httpUrl = 'api/pay/v1/pay_sign_ali'
	} else if (payInfo.type == 'smallPay') {
		// 微信小程序支付
		httpUrl = 'api/pay/v1/small_pay_sign_wx'
	}
	$http.get(httpUrl, {
		orderNo: payInfo.orderNo
	}).then(data => {
		let payData = {
			success: function(res) {
				callback && callback({
					success: true,
					data: res
				});
				console.log('success:' + JSON.stringify(res));
			},
			fail: function(err) {
				callback && callback({
					success: false,
					data: err
				});
				console.log('fail:' + JSON.stringify(err));
			}
		};
		if (payInfo.type == 'smallPay') {
			// 小程序
			payData.provider = 'wxpay';
			payData.timeStamp = data.timeStamp;
			payData.nonceStr = data.nonceStr;
			payData.package = data.package;
			// payData.package = "prepay_id=" + data.prepayid;
			payData.signType = "MD5";
			payData.paySign = data.sign;
		} else if (payInfo.type == 'wxpay') {
			// app微信
			payData.provider = 'wxpay';
			payData.orderInfo = data;
		} else if (payInfo.type == 'alipay') {
			// app 支付宝
			payData.provider = 'alipay';
			payData.orderInfo = data;
		} else if (payInfo.type == 'baidu') {
			payData.provider = 'baidu';
			payData.orderInfo = data;
		}
		console.log("支付参数", payData);
		uni.requestPayment(payData);
	}, err => {
		callback && callback({
			success: false,
			data: err
		});
	});
}
// 支付统一分配
export const setPayAssign = function(orderInfo, callback) {
	orderInfo.price = orderInfo.price || orderInfo.pricePay;
	orderInfo.title = orderInfo.title || orderInfo.orderTitle;
	//支付
	// #ifdef APP-PLUS
	uni.navigateTo({
		url: '/pages/home/weChatPay?orderNo=' + orderInfo.orderNo + '&price=' + orderInfo.price + '&title=' + orderInfo.title
	});
	// #endif 
	// #ifdef MP-WEIXIN
	setPay({
		...orderInfo,
		type: "smallPay"
	}, res => {
		if(res.success){
			uni.redirectTo({
				url: "/pages/shopCar/paySuccess?orderNo=" + orderInfo.orderNo
			});
		}
	});
	// #endif
	// #ifdef H5
	if (getBrowser() === '微信') {
		wxPublicPay({
			orderNo: orderInfo.orderNo
		}, function(){
			uni.redirectTo({
				url: "/pages/shopCar/paySuccess?orderNo=" + orderInfo.orderNo
			});
		});
	} else {
		appMutual('setJumpPay', orderInfo);
	}
	// #endif
}
// 获取地址信息 （微信小程序、APP、公众号）
export const getLatLon = function(tip){
	return new Promise((resolve, reject) => {
		const successProcess = function(res){
			store.commit("setCurrentAddress", {
				latitude: res.latitude,
				longitude: res.longitude
			});
			resolve(res);
		};
		const errProcess = function(err){
			reject(err);
			if(tip){
				uni.showToast({
					title: err,
					icon: "none"
				});
			}
		};
		// #ifdef H5
		getLatLonH5(successProcess,errProcess);
		// #endif
		// #ifndef H5
		getAppWxLatLon(successProcess,errProcess);
		// #endif
	});
}

// 地址逆解析
export const setLatLng = (address) =>{
	return new Promise((resolve, reject) => {
		uni.request({
			url: 'https://restapi.amap.com/v3/geocode/geo?parameters',
			method: 'GET',
			changeOrigin:true,
			data: {
				key: "b113400e3d50d12fdb9c6a12deaa2edb",
				address
			},
			success: (res) => {
				resolve(res);
			}
		})
	})
}

// 上传图片
export const uploadImage = (filePath) =>{
	let storeUserInfo = uni.getStorageSync("userInfo");
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: base.baseUrl + 'api/upload',
			filePath,
			name:'file',
			header:{
				"token": storeUserInfo.token
			},
			success: (res) => {
				let data = JSON.parse(res.data);
				resolve(data.data);
			}
		})
	})
}

// 支付
function obj2str (args) {
    var keys = Object.keys(args)
    keys = keys.sort() //参数名ASCII码从小到大排序（字典序）；
    var newArgs = {}
    keys.forEach(function (key) {
      if (args[key] != "" && args[key] != 'undefined') {  //如果参数的值为空不参与签名；
        newArgs[key] = args[key]  //参数名区分大小写；
      }
      
    })
    var string = ''
    for (var k in newArgs) {
      string += '&' + k + '=' + newArgs[k]
    }
    string = string.substr(1)
    return string
  }
  // 支付测试
  export const pay1 = (orderInfo, provider = 'wxpay') =>{
  	return new Promise((resolve, reject) => {
  		
	resolve(orderInfo);

  	})
  }
// 支付
export const pay = (orderInfo, provider = 'wxpay') =>{
	return new Promise((resolve, reject) => {
		
		var before={
				"appId": orderInfo.appId, // 应用ID（AppID）
				// "partnerid": orderInfo.partnerid, // 商户号（PartnerID）
				// "prepayid": orderInfo.prepayid, // 预支付交易会话ID
				"package": orderInfo.package, // 固定值
				// "package": "prepay_id=" + orderInfo.prepayid, // 固定值
				"nonceStr": orderInfo.nonceStr, // 随机字符串
				"timeStamp": orderInfo.timeStamp, // 时间戳（单位：秒）
				"signType":orderInfo.signType
			}
		var after=md5(obj2str(before)+"&key=qhdKgJTzNaCww5svKrbRnxaXkg26wVN3").toUpperCase()
		console.log(after)
		WeixinJSBridge.invoke(
			"getBrandWCPayRequest", {
				"appId": orderInfo.appId, // 应用ID（AppID）
				// "partnerid": orderInfo.partnerid, // 商户号（PartnerID）
				// "prepayid": orderInfo.prepayid, // 预支付交易会话ID
				"package": orderInfo.package, // 固定值
				// "package": "prepay_id=" + orderInfo.prepayid, // 固定值
				"nonceStr": orderInfo.nonceStr, // 随机字符串
				"timeStamp": orderInfo.timeStamp, // 时间戳（单位：秒）
				// "paySign": after, // 签名，这里用的 MD5 签名
				"paySign": orderInfo.paySign, // 签名，这里用的 MD5 签名
				"signType":orderInfo.signType
			},
			function(res1) {
				// uni.showToast({
				// 	title:res1.err_msg,
				// 	icon:'none'
				// })
				// uni.showToast({
				// 	title:res1.err_msg,
				// 	icon:'none'
				// })
				if (res1.err_msg == "get_brand_wcpay_request:ok") {
					// console.log('success:' + JSON.stringify(res));
					resolve(res1);
				}
			}
		);
		
		// uni.requestPayment({
		// 	provider,
		// 	orderInfo,
		// 	success: (res) => {
		// 		uni.showToast({
		// 			icon: 'success',
		// 			title: '支付成功'
		// 		})
		// 		resolve(res);
		// 	},
		// 	fail: (err) => {
		// 		console.log(err)
		// 		uni.showToast({
		// 			icon: 'none',
		// 			title: '取消支付'
		// 		})
		// 	},
		// 	complete: () => {
				
		// 	}
		// })
	})
}
/* export const pay = (orderInfo, provider = 'wxpay') =>{
	return new Promise((resolve, reject) => {
		uni.requestPayment({
			provider,
			orderInfo,
			success: (res) => {
				uni.showToast({
					icon: 'success',
					title: '支付成功'
				})
				resolve(res);
			},
			fail: (err) => {
				console.log(err)
				uni.showToast({
					icon: 'none',
					title: '取消支付'
				})
			},
			complete: () => {
				
			}
		})
	})
} */
// 倒计时
export const showtime = function (endtime) {
    var nowtime = new Date(),  //获取当前时间
        endtime = new Date(endtime);  //定义结束时间
    var lefttime = endtime.getTime() - nowtime.getTime(),  //距离结束时间的毫秒数
        leftd = Math.floor(lefttime/(1000*60*60*24)),  //计算天数
        lefth = Math.floor(lefttime/(1000*60*60)%24),  //计算小时数
        leftm = Math.floor(lefttime/(1000*60)%60),  //计算分钟数
        lefts = Math.floor(lefttime/1000%60);  //计算秒数
	if( lefttime <= 0 ){
		return '已过期'
	}
    return leftd + "天" + lefth + ":" + leftm + ":" + lefts;  //返回倒计时的字符串
}
